import { ColumnProps } from 'antd/lib/table';

import { Row, Spin, Table, Button } from 'antd';

import React from 'react';
import { Link } from 'umi';
import { Order } from '../../model';
import { ListContext, List } from '..';
import router from 'umi/router';

export const payTypeMap = {
  0: '微信',
  1: '支付宝',
  2: 'apple pay',
};

export const sourceTypeMap = {
  0: 'PC',
  1: 'APP',
};

export const orderStatusMap = {
  0: '待付款',
  1: '待发货',
  2: '已发货',
  3: '已完成',
  4: '已关闭',
};

const columns: ColumnProps<Order>[] = [
  {
    title: '编号',
    dataIndex: 'id',
    align: 'center',
  },
  {
    title: '订单编号',
    dataIndex: 'orderSn',
    align: 'center',
  },
  {
    title: '提交时间',
    dataIndex: 'createTime',
    align: 'center',
  },
  {
    title: '用户账号',
    dataIndex: 'appUserName',
    align: 'center',
  },
  {
    title: '订单金额',
    dataIndex: 'totalAmount',
    align: 'center',
    render: value => `￥${value}`,
  },
  {
    title: '支付方式',
    dataIndex: 'payType',
    align: 'center',
    render: value => payTypeMap[value],
  },
  {
    title: '订单状态',
    dataIndex: 'status',
    align: 'center',
    render: value => orderStatusMap[value],
  },
  {
    title: '操作',
    key: 'actions',
    width: '200px',
    align: 'center',
    render: (_text, record) => (
      <ListContext.Consumer>
        {(list: List) => {
          const buttonTextMap = {
            0: '关闭订单',
            1: '订单发货',
            2: '订单跟踪',
            3: '订单跟踪',
            4: '删除订单',
          };
          const buttonActionMap = {
            0: () => {
              list.onOrderStatusChange({ ...record, status: 4 });
            },
            1: () => {
              list.onOrderDeliverModalShow(record);
            },
            2: () => {},
            3: () => {},
            4: () => {
              list.onTableRowRemove(record.id);
            },
          };
          return (
            <div className="horizon-button-group">
              <Link to={`/order/details?id=${record.id}`}>
                <Button>查看订单</Button>
              </Link>
              {record.status !== 2 && record.status !== 3 ? (
                <Button
                  type={record.status === 4 ? 'danger' : 'default'}
                  onClick={buttonActionMap[record.status]}
                >
                  {buttonTextMap[record.status]}
                </Button>
              ) : null}
            </div>
          );
        }}
      </ListContext.Consumer>
    ),
  },
];

export interface ListTableProps {
  orders: Order[];
  loading?: boolean;
}

export default (props => (
  <Row>
    <Spin spinning={props.loading}>
      <Table<Order> dataSource={props.orders} columns={columns} rowKey="id" bordered />
    </Spin>
  </Row>
)) as React.FC<ListTableProps>;
